#!/bin/bash

if [ $# -ne 1 ];then
	echo "Usage $0 kernel_module_dir_name"
	exit 1
fi

if [ "`id -u`" -ne 0 ]; then
        echo_red "You should be root to run this script"
        exit 1
fi

echo "Mv files and configure...."

cp -rn * /
chmod +x /bin/ethercat
chmod +x /sbin/ethercatctl
chmod +x /etc/init.d/ethercat

#mac_str="`ifconfig | grep HWaddr | awk '{print $5}'`"
#master_dev_str="`cat /etc/sysconfig/ethercat | grep MASTER0_DEVICE=`"
#if [ master_dev_str = 'MASTER0_DEVICE=""' ];then
#	master_dev_str=MASTER0_DEVICE="$mac_str"
#	echo $master_dev_str >> /etc/sysconfig/ethercat
#fi

#dev_module_str="`cat /etc/sysconfig/ethercat | grep DEVICE_MODULES=`"
#if [dev_module_str = 'DEVICE_MODULES=""' ];then
#	echo DEVICE_MODULES="generic" >> /etc/sysconfig/ethercat
#fi

eth_str="`ifconfig | grep eth | awk '{print $1}'`"
i=0
eth_list=""
for x in ${eth_str[@]} #Tarverse mac list
do
	eth_list[i]=$x
	let i++
done
mac_str="`ifconfig | grep HWaddr | awk '{print $5}'`"
echo "Mac List:"
i=0
for x in ${mac_str[@]} #Tarverse mac list
do
	echo $i ${eth_list[$i]} ":" $x
	let i++
done
echo -n "Please input num to bind to EtherCat Master:"
read num
i=0
for x in ${mac_str[@]}
do
	if [ $i -eq $num ];
	then
		break
	fi
done
echo "You choice the mac:" $x

master_dev_str=MASTER0_DEVICE="$x"
echo $master_dev_str >> /etc/sysconfig/ethercat
echo 'DEVICE_MODULES="generic"' >> /etc/sysconfig/ethercat

echo Mv files and configure finisned!!!

echo "Mv module dir to sys dir ..."

kernel_version="`cat /proc/version | awk '{print $3}'`"
if [ -d /lib/modules/$kernel_version ];
then
	mv /lib/modules/$kernel_version '/lib/modules/${kernel_version}_bak'
fi
mv  /$1 /lib/modules/$kernel_version
depmod
echo "Start test..."
/etc/init.d/ethercat restart




